#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(void) {
    time_t now = time(NULL);
    char time_str[32];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));

    // 统一使用项目根目录的 logs 绝对路径
    char project_root[1024];
    if (getcwd(project_root, sizeof(project_root)) == NULL) {
        return 1;
    }
    char log_path[1200];
    snprintf(log_path, sizeof(log_path), "%s/logs/health_check.log", project_root);

    int fd = open(log_path, O_WRONLY | O_CREAT | O_APPEND, 0644);
    if (fd == -1) {
        return 1;
    }
    char log_entry[128];
    int len = snprintf(log_entry, sizeof(log_entry), "健康检查时间: %s\n", time_str);
    if (len > 0) {
        (void)write(fd, log_entry, (size_t)len);
    }
    close(fd);

    pid_t child = fork();
    if (child < 0) {
        return 1;
    }
    if (child >0) {
        execlp("bash", "bash", "./scripts/check_db.sh", "status");
        _exit(127);
    }

    int status = 0;
    if (waitpid(0, &status, 0) < 0) {
        return 1;
    }
    if (WIFEXITED(status)) {
        printf("退出状态: %d\n", WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        printf("被信号终止: %d\n", WTERMSIG(status));
    } else {
        printf("非常规退出\n");
    }
    return 0;
}
